<?php
/**
 * Created by PhpStorm.
 * User: happy
 * Date: 19/4/22
 * Time: 上午9:13
 * redis 进程池,防止连接过多,一个进程池仅仅允许100个redis连接
 */
class redis_poolPlugin extends Plugin
{
    /**@var \Swoole\Coroutine\Channel */
    protected $pool;

    /**
     * RedisPool constructor.
     * @param int $size max connections
     */
    public function __construct()
    {
    }
     //初始化连接进程池大小
    public  function  init($size = 100,$config=[]){
        $this->pool = new \Swoole\Coroutine\Channel($size);
        for ($i = 0; $i < $size; $i++) {
            $option['password']='ddd';//https://wiki.swoole.com/wiki/page/762.html
           // swoole_redis->__construct(array $options = null);
            $redis = new \Swoole\Coroutine\Redis();
           // $res = $redis->connect('127.0.0.1', 6379);
            $res = $redis->connect($config['host'], $config['port']);
            // $redis->auth($config['pass']);
            if ($res == false) {
                throw new \RuntimeException("failed to connect redis server.");
            } else {
                $this->put($redis);
            }
        }
    }
   // 返回 \Swoole\Coroutine\Redis
    public function get()
    {
        return $this->pool->pop();
    }

public function put(\Swoole\Coroutine\Redis $redis)
{
    $this->pool->push($redis);
}
 //返回: void
public function close()
    {
        $this->pool->close();
        $this->pool = null;
    }

}